
#lang racket


;;;; 利用不动点求平方根
;;;; average-dump 函数当参数,并且返回一个函数

(define (abs x)
  "绝对值"
  (if (< x 0)
      (- x)
      x))
(define (close? x y )
  "判断 x y 是否接近"
  (< (abs (- x y))
     0.001))


(define (fix-point f)
  "固定点"
  (define (try old new)
    (if (close? old new)
        new
        (try new (f new))))

  (try 1.0 (f 1.0))
  )

(define (average x y )
  (/ (+ x y) 2.0))

(define (average-dump f)
  "阻尼平均"
  (lambda(x)
    (average x (f x))))

(define (sqrt1 x)
  "不动点求平方根"
  (fix-point (average-dump (lambda(a)
                             (/ x a)))))



(define (sqrt2 x)
  (fix-point (lambda(a)
               (average a (/ x a)))))


;; 开3次方
(define (sqrt3 x)
  (fix-point (average-dump (lambda(a)
                             (/ x (* a a))))))

(sqrt1 2)
(sqrt2 5)

;; 开3次方
(sqrt3 8)
(sqrt3 64)

